package com.example.generateddl.service.impl;

import com.alibaba.excel.EasyExcel;
import com.example.generateddl.pojo.PdmEntity;
import com.example.generateddl.service.DealWithExcelService;
import com.example.generateddl.tools.ExcelListener;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

@Service
public class DealWithExcelServiceImpl implements DealWithExcelService {
    @Override
    public List<PdmEntity> readExcelData(String filePath) {
        if (StringUtils.isNotBlank(filePath)) {
            try {
                FileInputStream fileInputStream = new FileInputStream(filePath);
                List<PdmEntity> pdmEntities = parseExcel(fileInputStream);
                return pdmEntities;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public String dealWithPdmEntities(String filePath) {
        int lastIndexOf = 0;
        if (filePath.contains("/")) {
            lastIndexOf = filePath.lastIndexOf("/");
        } else {
            lastIndexOf = filePath.lastIndexOf("\\");
        }
        String fileName = filePath.substring(lastIndexOf + 1);
        String tableName = fileName.split("\\.")[0].toLowerCase(Locale.ROOT);
        List<PdmEntity> pdmEntities = readExcelData(filePath);

        //创建表
        StringBuilder creatTable = new StringBuilder("CREATE TABLE").append(" ").append(tableName).append(" ( ");
        pdmEntities.forEach(i -> {
            i = replaceDataType(i);
            String notNull = StringUtils.isNotBlank(i.getNonEmpty()) ? "NOT NULL" : "";
            //insert_time增加默认时间
            String sysDate = ("insert_time".toUpperCase(Locale.ROOT)).equals(i.getCode().toUpperCase(Locale.ROOT))
                    && ("DATE".toUpperCase(Locale.ROOT)).equals(i.getDataType().toUpperCase(Locale.ROOT)) ?
                    "DEFAULT SYSDATE" : "";
            if (pdmEntities.indexOf(i) == pdmEntities.size() - 1) {
                creatTable.append(i.getCode()).append(" ").append(i.getDataType()).append(" ").append(sysDate).append(" ").append(notNull).append(" )").append(";");
            } else {
                creatTable.append(i.getCode()).append(" ").append(i.getDataType()).append(" ").append(sysDate).append(" ").append(notNull).append(",").append(" ");
            }
        });
        creatTable.append("\n").append("\n");
        //添加主键
        creatTable.append("ALTER TABLE ").append(tableName).append(" ADD PRIMARY KEY ( ");
        List<PdmEntity> primaryKeyEntities = pdmEntities.stream().filter(i -> StringUtils.isNotBlank(i.getPrimaryKey())).collect(Collectors.toList());
        primaryKeyEntities.forEach(i -> {
            if (primaryKeyEntities.indexOf(i) == primaryKeyEntities.size() - 1) {
                creatTable.append("\"").append(i.getCode().toUpperCase(Locale.ROOT)).append("\"").append(" )").append(";");
            } else {
                creatTable.append("\"").append(i.getCode().toUpperCase(Locale.ROOT)).append("\"").append(",").append(" ");
            }
        });
        creatTable.append("\n").append("\n");

        //添加注释
        pdmEntities.forEach(i -> {
            creatTable.append("COMMENT ON COLUMN ")
                    .append(tableName).append(".")
                    .append(i.getCode().toUpperCase(Locale.ROOT))
                    .append(" IS '").append(i.getName()).append("';");
            creatTable.append("\n");
        });

        return creatTable.toString();
    }

    private PdmEntity replaceDataType (PdmEntity pdmEntity) {
        String source = "DECIMAL";
        String target = "NUMBER";
        String dataType = pdmEntity.getDataType();
        if (dataType.toUpperCase(Locale.ROOT).contains(source)) {
            String replace = dataType.replace(source, target);
            pdmEntity.setDataType(replace);
        }
        return pdmEntity;
    }

    private List<PdmEntity> parseExcel(InputStream inputStream) {
        ExcelListener excelListener = new ExcelListener();
        EasyExcel.read(inputStream, PdmEntity.class, excelListener).sheet().doRead();
        return excelListener.getPdmEntityList();
    }
}
